package com.dankegongyu.demo.http.http.interceptor;

import android.text.TextUtils;

import com.dankegongyu.demo.http.http.HttpError;
import com.dankegongyu.demo.http.http.HttpException;
import com.dankegongyu.demo.http.http.api.Api;
import com.dankegongyu.lib.http.exception.ServerException;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import androidx.annotation.NonNull;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * OkHttp拦截器
 *
 * @author wpq
 * @version 1.0
 */
public class ParseInterceptor implements Interceptor {
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request().newBuilder().build();
        if (request.url() != null) {
            String url = request.url().toString();
            // 如果url是非蛋壳Api的，则不需要执行下面签名等操作
            if (url != null && !url.contains(Api.BASE_URL)) {
                return chain.proceed(request);
            }
        }

        Response response = null;
        try {
            response = chain.proceed(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (response == null) {
            throw new ServerException("response is null");
        }
        if (response.code() != 200) {
            ResponseBody body = response.body();
            throw new HttpException(body == null ? "Response code is not 200!" : body.string());
        }

        MediaType contentType = null;
        JSONObject originalJson = null;
        String originalContent = null;
        try {
            //noinspection ConstantConditions
            contentType = response.body().contentType();
            //先解析一遍json数据，根据code和msg手动改状态码和描述
            //noinspection ConstantConditions
            originalContent = response.body().string();

//            Logger.e(originalContent);
            // {"code":"0000","msg":"成功","data":{"test": ""}}
            originalJson = new JSONObject(originalContent);
        } catch (JSONException e) {
//            e.printStackTrace();
        }

        // 如果response数据是code msg data格式，说明是新api，这里做下预解析
        if (originalJson != null && originalJson.has("code")) {
            String responseCode = HttpError.ERROR_CODE_DEFAULT;
            if (originalJson.has("code")) {
                responseCode = originalJson.optString("code");
            }

            String message = "";
            if (originalJson.has("msg")) {
                message = originalJson.optString("msg");
            }

            String body = "";
            if (originalJson.has("data")) {
                body = originalJson.optString("data");
            }

            // 公司接口决定：0000表示成功，否则均为失败
            int code;
            if ("0000".equals(responseCode)) {
                code = 200;
            } else {
                throw new ServerException(responseCode, message, body);
//                throw new HttpException(createErrorJson(responseCode, message));
            }

            if ("null".equalsIgnoreCase(body) || TextUtils.isEmpty(body)) {
                body = "{}"; // 如果"data":null，则将null置为"{}"，方便解析data
            }

            return response.newBuilder()
                    .code(code)
                    .message(message)
                    .body(ResponseBody.create(contentType, body))
                    .build();
        }
        // 如果不是code msg data格式，说明是旧api，直接返回即可
        return response.newBuilder()
                .body(ResponseBody.create(contentType, originalContent))
                .build();
    }

    private String createErrorJson(String code, String message) {
        HttpError httpError = new HttpError();
        httpError.businessCode = code == null || TextUtils.isEmpty(code.trim()) ? HttpError.ERROR_CODE_DEFAULT : code;
        httpError.description = message;
        return new Gson().toJson(httpError);
    }
}
